package com.qyhl.shop.shop.showcase;

import android.text.TextUtils;
import android.text.style.TextAppearanceSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.gyf.immersionbar.ImmersionBar;
import com.lihang.ShadowLayout;
import com.makeramen.roundedimageview.RoundedImageView;
import com.qyhl.shop.R;
import com.qyhl.shop.R2;
import com.qyhl.webtv.basiclib.base.BaseActivity;
import com.qyhl.webtv.basiclib.base.BaseIViewPresenter;
import com.qyhl.webtv.basiclib.utils.NetUtil;
import com.qyhl.webtv.basiclib.utils.SpanUtils;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.shop.ShopShowcaseBean;
import com.qyhl.webtv.commonlib.entity.shop.ShopShowcaseNoticeBean;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.weavey.loading.lib.LoadingLayout;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;
import com.zhy.adapter.recyclerview.wrapper.HeaderAndFooterWrapper;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

@Route(path = ARouterPathConstant.SHOP_SHOWCASE_LIST)
public class ShopShowcaseListActivity extends BaseActivity implements ShopShowcaseListContract.ShopShowcaseListView {
    @BindView(R2.id.recycler_view)
    RecyclerView recyclerView;
    @BindView(R2.id.refresh)
    SmartRefreshLayout refresh;
    @BindView(R2.id.load_mask)
    LoadingLayout loadMask;

    @Autowired(name = "shopId")
    int shopId;

    private ShopShowcaseListPresenter mPresenter;

    private CommonAdapter<ShopShowcaseBean> commonAdapter;

    private List<ShopShowcaseBean> mDataList = new ArrayList<>();

    private HeaderAndFooterWrapper<ShopShowcaseBean> headerAndFooterWrapper;

    private int page = 1;

    private ShopShowcaseNoticeBean noticeBean;

    @Override
    protected int getContentView() {
        return R.layout.shop_activity_showcase_list;
    }

    @Override
    protected void setImmersionBar(ImmersionBar mImmersionBar) {
        setDefaultImmerBar();
    }

    @Override
    protected BaseIViewPresenter initBaseIViewPresenter() {
        return null;
    }

    @Override
    protected void init() {
        loadMask.setStatus(LoadingLayout.Loading);

        mPresenter = new ShopShowcaseListPresenter(this);

        refresh.setRefreshHeader(new MaterialHeader(this));
        refresh.setRefreshFooter(new ClassicsFooter(this));
        refresh.setEnableLoadMore(true);

        recyclerView.setLayoutManager(new GridLayoutManager(this, 2));
        commonAdapter = new CommonAdapter<ShopShowcaseBean>(this, R.layout.shop_item_showcase_list, mDataList) {
            @Override
            protected void convert(ViewHolder holder, ShopShowcaseBean bean, int position) {
                holder.setText(R.id.title, bean.getItemName());

                RoundedImageView cover = holder.getView(R.id.cover);
                Glide.with(ShopShowcaseListActivity.this)
                        .load(bean.getItemPic())
                        .apply(new RequestOptions().error(R.drawable.cover_normal_default).placeholder(R.drawable.cover_normal_default))
                        .into(cover);

                if (TextUtils.isEmpty(bean.getTag())) {
                    holder.setVisible(R.id.tag, false);
                } else {
                    holder.setVisible(R.id.tag, true);
                    holder.setText(R.id.tag, bean.getTag());
                }

                if (bean.getNormList() != null && bean.getNormList().size() > 0) {
                    if (bean.getNormList().size() == 1) {
                        holder.setVisible(R.id.norm, false);
                        setPrice(holder, bean, false);
                    } else {
                        holder.setVisible(R.id.norm, true);
                        setPrice(holder, bean, true);
                    }
                } else {
                    holder.setVisible(R.id.norm, false);
                }


                holder.setOnClickListener(R.id.norm, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        ShopShowcasePopupView shopShowcasePopupView = new ShopShowcasePopupView(ShopShowcaseListActivity.this, bean);
                        shopShowcasePopupView.showPopupWindow();
                    }
                });

            }
        };

        mPresenter.getNotice(shopId);

    }

    private void setPrice(ViewHolder holder, ShopShowcaseBean showCaseBean, boolean isMore) {
        SpanUtils spUtils = new SpanUtils(ShopShowcaseListActivity.this);
        spUtils.append("¥").setSpans(new TextAppearanceSpan(ShopShowcaseListActivity.this, R.style.shop_showcase_list_price_one))
                .append(StringUtils.splitDouble(showCaseBean.getNormList().get(0).getPrice(), true)).setSpans(new TextAppearanceSpan(ShopShowcaseListActivity.this, R.style.shop_showcase_list_price_two))
                .append(StringUtils.splitDouble(showCaseBean.getNormList().get(0).getPrice(), false)).setSpans(new TextAppearanceSpan(ShopShowcaseListActivity.this, R.style.shop_showcase_list_price_one));

        if (isMore) {
            spUtils.appendSpace(2)
                    .append("起").setSpans(new TextAppearanceSpan(ShopShowcaseListActivity.this, R.style.shop_showcase_price_one));
        }

        TextView price = holder.getView(R.id.price);
        price.setText(spUtils.create());
    }

    @Override
    protected void setListener() {
        loadMask.setOnReloadListener(new LoadingLayout.OnReloadListener() {
            @Override
            public void onReload(View v) {
                loadMask.setReloadButtonText("加载中...");
                page = 1;
                mPresenter.getNotice(shopId);
            }
        });

        refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                page = 1;
                mPresenter.getNotice(shopId);
            }
        });

        refresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                mPresenter.getList(shopId, page);
            }
        });

        commonAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder viewHolder, int i) {
                int position;
                if (noticeBean == null || TextUtils.isEmpty(noticeBean.getTitle())) {
                    position = i;
                } else {
                    position = i - 1;
                }
                ARouter.getInstance()
                        .build(ARouterPathConstant.SHOP_SHOWCASE_DETAIL)
                        .withInt("itemId", mDataList.get(position).getId())
                        .navigation();
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder viewHolder, int i) {
                return false;
            }
        });
    }

    @Override
    public void setList(List<ShopShowcaseBean> beanList) {
        loadMask.setStatus(LoadingLayout.Success);
        loadMask.setReloadButtonText("点击重试~");
        if (beanList == null) {
            setError("暂无任何内容!");
            return;
        }
        if (page != 1) {
            refresh.finishLoadMore();
        } else {
            refresh.finishRefresh();
            mDataList.clear();
        }
        page++;
        mDataList.addAll(beanList);
        commonAdapter.notifyDataSetChanged();
    }

    @Override
    public void setNotice(ShopShowcaseNoticeBean bean) {
        noticeBean = bean;
        if (bean == null || TextUtils.isEmpty(bean.getTitle())) {
            recyclerView.setAdapter(commonAdapter);
        } else {
            View headView = LayoutInflater.from(this).inflate(R.layout.shop_header_showcase_list, null);
            TextView noticeTv = headView.findViewById(R.id.notice);
            headerAndFooterWrapper = new HeaderAndFooterWrapper<>(commonAdapter);
            headerAndFooterWrapper.addHeaderView(headView);

            recyclerView.setAdapter(headerAndFooterWrapper);

            noticeTv.setText(bean.getTitle());
        }

        mPresenter.getList(shopId, page);
    }

    @Override
    public void setError(String msg) {
        if (page != 1) {
            refresh.finishLoadMore();
            if (!NetUtil.isNetworkAvalible(this)) {
                showToast("网络异常，请检查您的网络！");
            } else if (msg.contains("暂无")) {

            } else {
                showToast(msg);
            }
        } else {
            refresh.finishRefresh();
            loadMask.setStatus(LoadingLayout.Error);
            loadMask.setReloadButtonText("点击重试~");
            if (!NetUtil.isNetworkAvalible(this)) {
                loadMask.setErrorImage(R.drawable.error_network);
                loadMask.setErrorText("网络异常，请检查您的网络！");
            } else if (msg.contains("暂无")) {
                loadMask.setErrorImage(R.drawable.empty_content);
                loadMask.setErrorText(msg);
            } else {
                loadMask.setErrorImage(R.drawable.error_content);
                loadMask.setErrorText(msg);
            }
        }
    }


    @OnClick(R2.id.back_btn)
    public void onClick() {
        finish();
    }
}
